/**
 *
 */
package org.ibase4j.system.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.ibase4j.jwt.utils.StringUtils;
import org.ibase4j.system.model.SysMenu;
import org.ibase4j.system.model.SysUser;
import org.ibase4j.system.model.SysUserRole;
import org.ibase4j.system.service.SysAuthorizeService;
import org.ibase4j.system.service.SysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import top.ibase4j.core.base.BaseController;
import top.ibase4j.core.support.Assert;
import top.ibase4j.core.support.http.HttpCode;
import top.ibase4j.core.util.SecurityUtil;
import top.ibase4j.core.util.UploadPathUtil;
import top.ibase4j.core.util.UploadUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户管理控制器
 *
 * @author ShenHuaJie
 * @version 2016年5月20日 下午3:12:12
 */
@RestController
@Api(value = "用户管理", description = "用户管理")
@RequestMapping(value = "/user")
public class SysUserController extends BaseController<SysUser, SysUserService> {
    private SysAuthorizeService sysAuthorizeService;

    // 查询用户
    @Override
    @ApiOperation(value = "查询用户")
    @RequiresPermissions("sys.base.user.read")
    @PostMapping(value = "/read/page")
    public Object query(ModelMap modelMap, @RequestBody Map<String, Object> param) {
        Object pageResult = service.queryApp(param);
        return setSuccessModelMap(modelMap, pageResult);
    }

    // 查询用户
    @Override
    @ApiOperation(value = "查询用户")
    @RequiresPermissions("sys.base.user.read")
    @GetMapping(value = "/read/list")
    public Object queryList(ModelMap modelMap, @RequestBody Map<String, Object> param) {
        return super.queryList(modelMap, param);
    }

    // 用户详细信息
    @ApiOperation(value = "用户详细信息")
    @RequiresPermissions("sys.base.user.read")
    @GetMapping(value = "/read/detail")
    public Object get(ModelMap modelMap, @RequestBody SysUser param) {
        SysUser result = service.queryById(param.getId());
        result.setPassword(null);
        return setSuccessModelMap(modelMap, result);
    }

    // 用户详细信息
    @Override
    @PostMapping(value = "/delete")
    @ApiOperation(value = "删除用户")
    @RequiresPermissions("sys.base.user.delete")
    public Object delete(ModelMap modelMap, @RequestBody SysUser param) {
        return super.delete(modelMap, param);
    }

    // 当前用户
    @ApiOperation(value = "当前用户信息")
    @GetMapping(value = "/read/promission")
    public Object promission(ModelMap modelMap) {
        Long id = getCurrUser().getId();
        SysUser sysUser = service.queryById(id);
        sysUser.setPassword(null);
        modelMap.put("user", sysUser);
        List<?> roles = sysAuthorizeService.getRolesByUserId(id);
        modelMap.put("roles", roles);
        List<String> permission = sysAuthorizeService.queryPermissionByUserId(id);
        List<?> permissionNew = permission.stream().filter(str -> str != null).map(string -> {
            return string.replaceAll("\\.", "_");
        }).collect(Collectors.toList());
        modelMap.put("permission", permissionNew);
        List<?> menus = sysAuthorizeService.queryAuthorizeByUserId(id);
        modelMap.put("menus", menus);
        return setSuccessModelMap(modelMap);
    }

    // 当前用户
    @ApiOperation(value = "当前用户信息菜单")
    @GetMapping(value = "/getMenu")
    public Object getMenu(ModelMap modelMap) {
        Long id = getCurrUser().getId();
        List<SysMenu> menus = sysAuthorizeService.queryAuthorizeByUserId(id);
        modelMap.put("menus", menus);
        return setSuccessModelMap(modelMap);
    }

    @Override
    @PostMapping(value = "/save")
    @ApiOperation(value = "修改用户信息")
    @RequiresPermissions("sys.base.user.update")
    public Object update(ModelMap modelMap, @RequestBody SysUser param) {
        Assert.isNotBlank(param.getAccount(), "ACCOUNT");
        Assert.length(param.getAccount(), 3, 15, "ACCOUNT");
        if (param.getEnable() == null) {
            param.setEnable(0);
        }
        SysUser page = super.save(param);
        if (StringUtils.isNotEmpty(param.getRoleList())) {
            List<Integer> roleIds = param.getRoleList();
            List<SysUserRole> sysUserRoles = new ArrayList<>();
            for (Integer roleId : roleIds) {
                if (roleId == null) continue;
                SysUserRole userRole = new SysUserRole(page.getId(), roleId.longValue());
                userRole.setCreateBy(getCurrUser().getId());
                userRole.setUpdateBy(getCurrUser().getId());
                userRole.setCreateTime(new Date());
                userRole.setUpdateTime(new Date());
                sysUserRoles.add(userRole);
            }
            if (StringUtils.isNotEmpty(sysUserRoles)) sysAuthorizeService.updateUserRole(sysUserRoles);
        }
        return super.setSuccessModelMap(modelMap);
    }

    // 当前用户
    @ApiOperation(value = "当前用户信息")
    @GetMapping(value = "/read/current")
    public Object current(ModelMap modelMap) {
        SysUser result = service.queryById(getCurrUser().getId());
        result.setPassword(null);
        return setSuccessModelMap(modelMap, result);
    }

    @ApiOperation(value = "修改个人信息")
    @PostMapping(value = "/update/person")
    public Object updatePerson(ModelMap modelMap, @RequestBody SysUser param) {
        param.setId(getCurrUser().getId());
        param.setPassword(null);
        Assert.isNotBlank(param.getAccount(), "ACCOUNT");
        Assert.length(param.getAccount(), 3, 15, "ACCOUNT");
        return super.update(modelMap, param);
    }

    @ApiOperation(value = "修改用户头像")
    @PostMapping(value = "/upload/avatar")
    public Object updateAvatar(HttpServletRequest request, ModelMap modelMap) {
        String uploadLogicType = "/avatar/"; //业务类型
        String pathDir = UploadPathUtil.getUploadOpenFileRoot() + uploadLogicType;
        List<String> fileNames = UploadUtil.uploadImageWithPath(request,pathDir,false);
        if (fileNames.size() > 0) {
            SysUser param = new SysUser();
            param.setId(getCurrUser().getId());
            String filePath = pathDir + fileNames.get(0);
            logger.info("上传文件保存位置==>" + filePath);
            String viewUrl = UploadPathUtil.getUploadViewUri()  + "openfile" + uploadLogicType;
            String avatarUrl = viewUrl + fileNames.get(0);
            logger.info("头像访问地址==>" + avatarUrl);
            param.setAvatar(avatarUrl);
            this.save(param);
            modelMap.put("url", avatarUrl);
            modelMap.put("name", "用户头像");
            return setSuccessModelMap(modelMap);
        } else {
            setModelMap(modelMap, HttpCode.BAD_REQUEST);
            modelMap.put("msg", "请选择要上传的文件！");
            return setSuccessModelMap(modelMap);
        }
    }

    // 修改密码
    @ApiOperation(value = "修改密码")
    @PostMapping(value = "/update/password")
    public Object updatePassword(ModelMap modelMap, @RequestBody SysUser param) {
        Assert.isNotBlank(param.getOldPassword(), "OLDPASSWORD");
        Assert.isNotBlank(param.getPassword(), "PASSWORD");
        String encryptPassword = SecurityUtil.encryptPassword(param.getOldPassword());
        SysUser sysUser = service.queryById(getCurrUser().getId());
        Assert.notNull(sysUser, "USER", param.getId());
        if (!sysUser.getPassword().equals(encryptPassword)) {
            throw new UnauthorizedException("原密码错误.");
        }
        sysUser.setPassword(SecurityUtil.encryptPassword(param.getPassword()));
        return super.update(modelMap, sysUser);
    }
}
